package com.daniel.fun;

import cn.hutool.json.JSONUtil;
import lombok.Data;
import lombok.ToString;
import lombok.extern.slf4j.Slf4j;

import java.util.function.Function;

/**
 * @Description: 公共方法的写法
 * @Author: sxgan
 * @Date: 2024-05-04 10:32
 * @Version: 1.0
 **/
@Slf4j
public class CommonFunMake {
    public static void main(String[] args) {
        CommonFunMake commonFunMake = new CommonFunMake();
        Student student = commonFunMake.commonFunOne("Zoey", "Code", Student.class, stu -> {
            log.info("回调函数执行当前传入参数为{}", stu);
            // 修改id为2
            stu.setId("2");
            stu.setName("Zoey");
            return stu;
        });
        log.info("返回结果为：{}", student.toString());
    }
    
    /**
     * 1、公共方法的写法
     *
     * @param param      普通参数
     * @param id         泛型id
     * @param type       返回值类型
     * @param dbFallback Function<ID, R> 回调函数，其中ID为输入参数类型，R为返回值类型
     * @param <R>        返回值类型声明
     * @param <ID>       泛型id类型声明
     * @return R
     */
    public <R, ID> R commonFunOne(String param, ID id, Class<R> type, Function<R, R> dbFallback) {
        // 普通参数
        log.info("普通参数->{},泛型id->{}", param, id);
        // 获取Json
        String studentJson = getStudentJson();
        log.info("返回数据Json形式为：{}", studentJson);
        
        // 相关回调方法执行
        R bean = JSONUtil.toBean(studentJson, type);
        R result = dbFallback.apply(bean);
        
        return result;
    }
    
    @Data
    class Student {
        private String id;
        private String name;
        private String age;
        
        public String toString() {
            return "Student{" +
                    "id='" + id + '\'' +
                    ", name='" + name + '\'' +
                    ", age='" + age + '\'' +
                    '}';
        }
    }
    
    public String getStudentJson() {
        Student student = new Student();
        student.setId("1");
        student.setName("张三");
        student.setAge("18");
        return JSONUtil.toJsonStr(student);
    }
}
